<?php
namespace app\common\logic;
use app\common\model\AuthClients as AuthClients;
use app\common\model\AuthCodes as AuthCodes;
use app\common\model\AuthTokens as AuthTokens;
class Oauth2 extends ABOauth2 {
    
  public function __construct() {
  }
  function __destruct() {
  }
  private function handleException($e) {
  }
  public function addClient($data) {
    $authClients = new AuthClients;
    
    $authClients->data($data);
    if($authClients->allowField(true)->save()) {
        return $authClients;
    }
    return NULL;
  }
  
  public function checkClientHas($mobile, $shortcode) {
      $authClients = new AuthClients;
        $result = $authClients->where('client_id', $mobile)
             ->where('client_secret',$shortcode)
             ->find();
        return $result;
  }
  protected function checkClientCredentials($client_id, $client_secret = NULL) {
    
    $authClients = new AuthClients;
    
    $result = $authClients->where('client_id', $client_id)->find();
    
    if($client_secret === NULL)
        return $result !== FALSE;
    
    return $result['client_secret'] == $client_secret;
  }
  protected function getRedirectUri($client_id) {
    
    $authClients = new AuthClients;
    
    $result = $authClients->where('client_id', $client_id)->find();
    
    if($client_secret === NULL)
        return $result !== FALSE;
    
    return $result['redirect_uri'];
  }
  protected function getAccessToken($oauth_token) {
    
    $authToken = new AuthTokens;
    
    $result = $authToken->where('oauth_token', $oauth_token)->find();
    
    return $result;
  }
  protected function setAccessToken($data) {
    $authToken = new AuthTokens;
    
    $authToken->data($data);
    if($authToken->allowField(true)->save()) {
        return $authToken->id;
    }
    return NULL;
  }
  
  protected function getSupportedGrantTypes() {
    return array(
      OAUTH2_GRANT_TYPE_AUTH_CODE,
    );
  }
  protected function getAuthCode($code) {
    
    $authCodes = new AuthCodes;
    
    $result = $authCodes->where('code', $code)->find();
    
    return $result;
  }
  protected function setAuthCode($data) {
    $authCodes = new AuthCodes;
    
    $authCodes->data($data);
    if($authCodes->allowField(true)->save()) {
        return $authCodes;
    }
    return NULL;
  }
  
  public function checkCodeHas($mobile, $shortcode) {
      $authClients = new AuthClients;
        $result = $authClients->where('client_id', $mobile)
             ->where('client_secret',$shortcode)
             ->find();
        return $result;
  }
  
  public function setTokenOver($uid) {
      $authToken = new AuthTokens;
      $result = $authToken->where('user_id', $uid)->delete();
      return $result;
  }
}
